<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class CheckPermission
{
    public function handle(Request $request, Closure $next)
    {
        // Extract the Bearer token from the Authorization header
        $token = $request->bearerToken();

        if (!$token) {
            return response()->json([
                'message' => 'Unauthorized: No token provided.'
            ], 401);
        }

         $tokenParts = explode('|', $token);
        if (count($tokenParts) !== 2) {
            return response()->json([
                'message' => 'Unauthorized: Invalid token format.'
            ], 401);
        }

        $tokenValue = $tokenParts[1];

        // Find the user associated with the token
        // Assuming tokens are stored in a 'personal_access_tokens' table with 'token' and 'user_id' columns
         $accessToken = \DB::table('personal_access_tokens')
            ->where('token', hash('sha256', $tokenValue))
            ->first();

        if (!$accessToken) {
            return response()->json([
                'message' => 'Unauthorized: Invalid token.'
            ], 401);
        }
        // Retrieve the user
        $user = User::where('id', $accessToken->tokenable_id)->first();

        if (!$user) {
            return response()->json([
                'message' => 'Unauthorized: User not found.'
            ], 401);
        }

        // Attach the user to the request for use in controllers
        $request->setUserResolver(function () use ($user) {
            return $user;
        });

        return $next($request);
    }
}